var globalSnap;
var areaElements;
var resultData;
var stationResultData;
var stationParamMap = new Map();
var lineRefMap = new Map();
var regionRefMap = new Map();
var regionBorderElements;
var ssTable;
var mapData;
var hoverTable;
var rootPath = "../";
var currentTimestamp = new Date().getTime();
var svgImageVer = 3;
(function () {
    init()
    function init() {
        console.log('init>>>')
        hoverTable = document.getElementById('area_status')
        let s = Snap()
        globalSnap = s
        Snap.load(rootPath + 'resources/line_updown_edit.svg?ver='+svgImageVer, function (f) {
            svg = f.select("svg").select("g");
            s.append(svg);
            s.append(f.select("svg"))
            //设置鼠标拖拽、滚动图像进行放大和缩小
            s.zpd();
            s.panTo('+280', '+0');
            //s.panTo('+100', '-150');
            getRegionData()
            getStationData()
            
        });

        //addSomeListener()
    }

    function getRegionData() {
        getJson("resources/result.json?ts="+currentTimestamp, function (json) {
            resultData = json
            //初始化区域名及区域简写对照MAP
            resultData.data.forEach(element => {
                if(!regionRefMap.has(element.region))
                {
                    regionRefMap.set(element.region,element.region_name)
                }
            })
            prepareMapData()
        })
    }

    function getStationData()
    {
        getJson("resources/station_view.json?ts="+currentTimestamp,function(json){
            stationResultData = json
            //初始化线路名及线路简写对照MAP
            stationResultData.data.forEach(element => {
                if(!lineRefMap.has(element.line))
                {
                    lineRefMap.set(element.line,element.line)
                }
            })
            prepareTableData()
        })
    }

    function prepareMapData() {
        mapData = new Map()
        //行政区与街道数据
        resultData.data.forEach(element => {
            mapData.set('area_' + element.region + "_" + element.street, element)
        });
        //行政区与街道图纸元素
        areaElements = globalSnap.selectAll('[id^="area"]')
        areaElements.forEach(ele => {
            try 
            {
                let data = mapData.get(ele.node.id)
                console.log("prepareMapData",ele.node.id)
                if (data.level3_percent >= 75) {
                    ele.node.setAttribute('style', "fill:#006400B0")
                } else if (data.level3_percent >= 50 && data.level3_percent < 75) {
                    ele.node.setAttribute('style', "fill:#FFFF0080")
                } else {
                    ele.node.setAttribute('style', "fill:#FF000080")
                }
            } catch (error) {
                console.log(error)
            }
        })
        //行政区边界图纸元素，元素放入全局MAP，减少后续筛选元素时的性能消耗
        regionBorderElements = globalSnap.selectAll('[id^="border_"]');
        addSomeListener()
    }

    function prepareTableData() {
        console.log(stationResultData.data)
        //to do
        // stationParamMap.set('region','pt')
        // selectDataFromStationView()
        initEasyuiElements()
        initPopper()
    }

    function selectDataFromStationView()
    {
        let result
        if(stationParamMap.size == 0)
        {
            //无参数时返回全量数据
            return stationResultData.data
        }
        if(stationParamMap.has('region') && stationParamMap.get('region'))
        {
            let region = stationParamMap.get('region')
            result = stationResultData.data.filter(item => item.region == region)
        }
        if(stationParamMap.has('line') && stationParamMap.get('line'))
        {
            let line = stationParamMap.get('line')
            if(result)
            {
                //结果不为空时从上次结果开始筛选
                result = result.filter(item => line.includes(item.line))
            }else{
                //结果为空时从原始数据筛选
                result = stationResultData.data.filter(item => line.includes(item.line))
            }
        }
        

        
        console.log('selectDataFromStationView>>>',result)
        return result
    }

    function getJson(path, callBack) {
        let url = rootPath + path
        var request = new XMLHttpRequest();
        request.open("get", url);/*设置请求方法与路径*/
        request.send(null);/*不发送数据到服务器*/
        request.onload = function () {/*XHR对象获取到返回信息后执行*/
            if (request.status == 200) {/*返回状态为200，即为数据获取成功*/
                var json = JSON.parse(request.responseText);
                console.log(json);
                callBack(json)
            }
        }
    }

    function addSomeListener() {
        console.log(areaElements)
        areaElements.forEach(ele => {
            //console.log(ele)
            ele.hover(hoverIn, hoverOut)
        });
    }

    function hoverIn(e) {
        //console.log('hover in', e)
        let ele = e.toElement
        ele.setAttribute('stroke',"#0000FF")
        let data = mapData.get(ele.id)
        let html = "<tr><td>区域</td><td>" + data.region_name + "</td></tr>" +
            "<tr><td>街镇</td><td>" + data.street_name + "</td></tr>" +
            "<tr><td>封控区</td><td>" + data.level1 + "</td></tr>" +
            "<tr><td>管控区</td><td>" + data.level2 + "</td></tr>" +
            "<tr><td>防范区</td><td>" + data.level3 + "</td></tr>" +
            "<tr><td>防范区占比</td><td>" + data.level3_percent + "%</td></tr>"
        hoverTable.innerHTML = html
    }

    function hoverOut(e) {
        //console.log('hover out', e)
        let ele = e.fromElement
        ele.setAttribute('stroke','')
    }

    /**
     * easyui控件初始化处理
     */
    function initEasyuiElements()
    {
        ssTable = $('#station_status_table')
        let ssTableOption = {
            data : stationResultData.data,
            rowStyler : function(index,row) {
                if(row.level3_percent >= 75)
                {
                    return "background-color:#006400B0;"
                }else if(row.level3_percent >=50 && row.level3_percent <75){
                    return "background-color:#FFFF0080"
                }else{
                    return "background-color:#FF000080"
                }
            }
        };
        ssTable.datagrid(ssTableOption)
        // stationParamMap.set('region','pt')
        // let sdata = selectDataFromStationView()
        // ssTable.datagrid('loadData',sdata)
    }
    /**
     * 
     * @param {*} data 
     * easyui datagrid控件加载数据（仅用于加载车站信息表）
     */

    function loadDataForDatagrid(data)
    {
        if(data)
            {
                ssTable.datagrid('loadData',data)
                showHideAreaElement(data)
                showHideBorderElement(data)
            }else{
                //为空时清空表格
                ssTable.datagrid('loadData',{total:0,rows:[]})
            }
    }

    /**
     * 显隐街道区域元素
     * @param {*} data 
     */
    function showHideAreaElement(data)
    {
        let areaArray = data.map((ele)=>{
            return "area_" + ele.region + "_" + ele.street
        })
        areaElements.forEach(ele=>{
            if(areaArray.includes(ele.node.id))
            {
                ele.node.setAttribute('display','')
            }else{
                ele.node.setAttribute('display','none')
            }
        })
    }
    /**
     * 显隐行政区边界元素
     * @param {*} region 
     */
    function showHideBorderElement(data)
    {
       let borderArrayOrigin = data.map((ele) => {
           return "border_" + ele.region
       })
       //元素去重
       let borderSet = new Set(borderArrayOrigin)
       console.log('borderset : ',borderSet)
       regionBorderElements.forEach(ele => {
           if(borderSet.has(ele.node.id))
           {
                ele.node.setAttribute('display','')
           }else{
                ele.node.setAttribute('display','none')
           }
       })
    }

    /**
     * popper控件初始化处理
     */
    function initPopper()
    {
        //popper触发元素：行政区列
        let regionButton = document.getElementById('region_column')
        let regionPopper = document.getElementById('region_popper')
        let regionPopperInstance = Popper.createPopper(regionButton, regionPopper,{placement:'bottom-start'})
        regionButton.addEventListener('click',(e)=>{
            let display = regionPopper.style.display
            if(display == 'none')
            {
                regionPopper.style.display = 'block'
            }else{
                regionPopper.style.display = 'none'
            }
        })
        //popper触发元素：线路列
        let lineButton = document.getElementById('line_column')
        let linePopper = document.getElementById('line_popper')
        let linePopperInstance = Popper.createPopper(lineButton, linePopper,{placement:'bottom-start'})
        lineButton.addEventListener('click',(e)=>{
            let display = linePopper.style.display
            if(display == 'none')
            {
                linePopper.style.display = 'block'
            }else{
                linePopper.style.display = 'none'
            }
        })

        //popper显示区域元素初始化
        //行政区下拉列表
        let regionSelect = document.getElementById('region_select')
        regionSelect.addEventListener('change',(e)=>{
            console.log('region select',e)
            let value = e.target.value
            //行政区改变时重置线路选择条件
            stationParamMap.delete('line')
            if(value == "all")
            {
                stationParamMap.delete('region')
            }else{
                stationParamMap.set('region',value)
            }
            let data = selectDataFromStationView()
            if(data)
            {
                let lineArr = []
                data.forEach((ele)=>{
                    if(!lineArr.includes(ele.line))
                    {
                        lineArr.push(ele.line)
                    }
                })
                console.log(lineArr)
                regenerateSelect('line_select',lineArr,lineRefMap)
            }
            loadDataForDatagrid(data)
        })
        //线路下拉列表
        let lineSelect = document.getElementById('line_select')
        lineSelect.addEventListener('change',(e)=>{
            console.log('line select',e)
            let value = e.target.value
            let queryLine = []
            if(value == "all")
            {
                let options = lineSelect.options
                for(let i = 0; i < options.length ; i++)
                {
                    queryLine.push(options[i].value)
                }
            }else{
                queryLine.push(value)
            }
            stationParamMap.set('line',queryLine)
            let data = selectDataFromStationView()
            loadDataForDatagrid(data)
        })
    }

    function regenerateSelect(domId,data,ref)
    {
        let parentDom = document.getElementById(domId)
        parentDom.innerHTML=''
        parentDom.insertAdjacentHTML("beforeend","<option value='all'>全部</option>")
        data.forEach(element => {
            parentDom.insertAdjacentHTML("beforeend","<option value='"+ element +"'>"+ ref.get(element) +"</option>")
        })

    }
})()